﻿using System;
using System.Collections.Generic;
using System.Windows.Browser;

namespace $YourCompany$.$safeprojectname$_Xap.Utilities
{
    public class ClientAPI
    {
        //define delegate event signature that matches javascript
        public delegate void ControlMethodDelegate(object payload, object context, object request);

        private static ScriptObject _xmlhttp;
        public static void InvokeControlMethod(string callbackID, string method, IDictionary<string, object> arguments, ControlMethodDelegate successFunc, ControlMethodDelegate failFunc)
        {
            //get a reference to javascript dnn.xmlhttp object
            if (_xmlhttp == null)
                _xmlhttp = (ScriptObject)HtmlPage.Window.Eval("dnn.xmlhttp");
            _xmlhttp.Invoke("callControlMethod", callbackID, method, DictionaryToScriptObject(arguments), successFunc, failFunc);
        }

        private static ScriptObject DictionaryToScriptObject(IDictionary<string, object> dict)
        {
            if (dict == null)
                return null;
            var obj = HtmlPage.Window.CreateInstance("Object");
            foreach (var key in dict.Keys)
                obj.SetProperty(key, dict[key]);
            return obj;
        }

    }
}
